﻿namespace Digitalmes.Gallery.Services;

/// <summary>
/// 导航菜单服务。
/// </summary>
public sealed class NavigationViewService(ILogger<NavigationViewService> logger) : INavigationViewService
{
    private readonly List<NavigationViewItem> _navigationViews = [];

    private readonly ILogger _logger = logger;

    public IReadOnlyList<NavigationViewItem> GetNavigationViews()
    {
        if (_navigationViews.Count > 0)
        {
            return _navigationViews;
        }
   
        var path = Path.Combine(AppContext.BaseDirectory, "Assets", "Config", "navigations.json");
        if (!Path.Exists(path))
        {
            _logger.LogWarning("没有找到指定的菜单文件，文件路径：{Path}", path);
            return _navigationViews;
        }

        var context = File.ReadAllText(path);
        try
        {
            var navItems = context.FromJson<List<NavigationItem>>();
            if (navItems == null)
            {
                return _navigationViews;
            }

            var menus = navItems.Select(m => new NavigationViewItem
            {
                Content = m.Title,
                Icon = new SymbolIcon { Symbol = Enum.Parse<SymbolRegular>(m.Icon) },
                TargetPageType = Type.GetType($"Digitalmes.Gallery.Views.Pages.{m.Page}"),
            }).ToArray();

            _navigationViews.AddRange(menus);
            return _navigationViews;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导航菜单解析异常");
            throw;
        }
    }

    public void Reload()
    {
        _navigationViews.Clear();
    }
}
